﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Irvin_Engine;

namespace Irvin_Engine.Sound
{
    public class Sound
    {
        string nameFile = "";
        float volumeDefault = 0.0f;
        float pitch = 0.0f;
        float pan = 0.0f;
        SoundEffect sound = null;
        List<SoundInstance> soundInstances = new List<SoundInstance>();

        public List<SoundInstance> SoundInstances
        {
            get { return soundInstances; }
        }

        public Sound()
            :this("", 0.0f, 0.0f, 0.0f)
        {
        }
        public Sound(string _fileSound, float _volume, float _pitch, float _pan)
        {
            nameFile = _fileSound;
            volumeDefault = _volume;
            sound = Kernel.GetInstance().Content.Load<SoundEffect>(_fileSound);
        }

        public void Play(bool _inOtherChannel)
        {
            if (!_inOtherChannel)
            {
                SoundInstance newSoundInstance = new SoundInstance(volumeDefault, pan, sound, true);
                soundInstances.Add(newSoundInstance);
            }

            sound.CreateInstance();
            //sound.Play(volumeDefault, pitch, pan);
        }

        public void Update(GameTime gameTime)
        {
            for (int i = 0; i < soundInstances.Count; i++)
            {
                soundInstances[i].Update(gameTime);
                if (soundInstances[i].IsStopped)
                    soundInstances.RemoveAt(i);
            }
        }

    }

    public class SoundInstance
    {
        SoundEffectInstance soundEffect = null;
        float volume = 0.0f;
        float pan = 0.0f;
        bool isPlaying = true;
        bool isStopped = false;

        public bool IsStopped { get{ return isStopped; } }

        public SoundInstance(float _volume, float _pan, SoundEffect _sound, bool _playImmediate)
        {
            isPlaying = _playImmediate;
            volume = _volume;
            pan = _pan;
            soundEffect = _sound.CreateInstance();
            if (_playImmediate)
            {
                Play();
            }
        }

        public void Play()
        {
            soundEffect.Volume = volume;
            soundEffect.Pan = pan;
            soundEffect.Play();
        }

        public void Update(GameTime gameTime)
        {
            if (soundEffect.State == SoundState.Stopped || soundEffect.IsDisposed)
            {
                isStopped = true;
            }
        }
    }
}
